class Attachment < ActiveRecord::Base
  belongs_to :post
  belongs_to :advertisment
  belongs_to :event
  belongs_to :query
  
  def file
    File.join("#{RAILS_ROOT}/attachments/#{self.id}",self.filename)
  end

  def file=(upload)
    if upload.class == Tempfile or upload.class == ActionController::UploadedStringIO or upload.class == ActionController::UploadedTempfile
      file_repository = FileUtils.mkdir_p "#{RAILS_ROOT}/attachments/#{self.id}"
      File.open(File.join(file_repository,upload.original_filename), "w") do |file|
        upload.rewind if upload.respond_to?(:rewind)
        file.write(upload.read)
      end
      self.filename = upload.original_filename
    end
  end
end
